package ae.pcfc.etks.online.wf;

import java.util.Collection;
import java.util.Map;
import java.util.Set;

import org.apache.commons.beanutils.BeanMap;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import ae.pcfc.etks.online.wf.service.client.vo.WFBaseVO;
import ae.pcfc.etks.online.wf.service.types.ArrayOfAnyType;
import ae.pcfc.etks.online.wf.service.types.ArrayOfVariable;
import ae.pcfc.etks.online.wf.service.types.ObjectFactory;
import ae.pcfc.etks.online.wf.service.types.Variable;

public class Utils {
	public static String getEndPointURI(Object target,
			Map<String, String> webServicesEndPointsMap) {
		String classKey = StringUtils.delete(
				ClassUtils.getShortName(target.getClass()), "Impl");
		String classURIValue = webServicesEndPointsMap.get(classKey);
		return classURIValue;
	}
	
	public static String appendDomainPrefix(String userName)
	{	
	    if(userName == null){
		return null;
	    }else if(!userName.contains(ConstantsWF.USER_PREFIX)){
		return ConstantsWF.USER_PREFIX+userName;
	    }else{
		return userName;
	    }
	}
	
	@SuppressWarnings("unchecked")
	public static <T extends WFBaseVO> ArrayOfVariable convertToWFVariable(T obj) {
		BeanMap beanMap = new BeanMap(obj);

		Set<String> objectAttributesSet = (Set<String>) beanMap.keySet();
		ObjectFactory factory = new ObjectFactory();
		ArrayOfVariable arrVar = factory.createArrayOfVariable();

		for (String keyAttribute : objectAttributesSet) {
			if (keyAttribute.equalsIgnoreCase("strUserName")
					|| keyAttribute.equalsIgnoreCase("strSummary")
					|| keyAttribute.equalsIgnoreCase("nIncidentNumber")
					|| keyAttribute.equalsIgnoreCase("strStepName")
					|| keyAttribute.equalsIgnoreCase("strMemo")
					|| keyAttribute.equalsIgnoreCase("class"))
				continue;

			Variable var = factory.createVariable();
			

			ArrayOfAnyType varValue = factory.createArrayOfAnyType();
			var.setObjVariableValue(varValue);
			
			Object valObj = beanMap.get(keyAttribute);
			System.out.println("WF variable name: "+keyAttribute+" value : "+valObj);
			TypeDescriptor typeDesc = TypeDescriptor.forObject(valObj);
			if (valObj != null) {
				if (typeDesc.isArray()) {
					varValue.getAnyType().addAll(
							CollectionUtils.arrayToList(valObj));
				} else if (typeDesc.isCollection()) {
					varValue.getAnyType().addAll((Collection<Object>) valObj);
				} else if (typeDesc.isMap()) {
					varValue.getAnyType().addAll(
							((Map<Object, Object>) valObj).values());
				} else {
					varValue.getAnyType().add(valObj);
				}
				var.setStrVariableName(keyAttribute);
				System.out.println("Setting WF variable name: "+keyAttribute+" value : "+valObj);
				arrVar.getVariable().add(var);
			}
			
		}
		
		return arrVar;
	}
}
